//
//  iTunesObserver.m
//  Do Not Disturb
//
//  Created by Chris Karr on 9/18/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "iTunesObserver.h"
#import "DNDDefines.h"

@implementation iTunesObserver

- (NSString *) getName
{
	return @"iTunes";
}

- (void) scan
{
	BOOL iTunesOpen = NO;
	
	NSWorkspace * workspace = [NSWorkspace sharedWorkspace];

	NSDictionary * active = [workspace activeApplication];

	if ([[active valueForKey:@"NSApplicationName"] isEqual:@"iTunes"])
		iTunesOpen = YES;

	NSArray * apps = [workspace launchedApplications];
	
	int i = 0;
	for (i = 0; i < [apps count]; i++)
	{
		if ([[[apps objectAtIndex:i] valueForKey:@"NSApplicationName"] isEqual:@"iTunes"])
			iTunesOpen = YES;
	}

	if (iTunesOpen)
	{
		NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"iTunes\"\n\
																			artist of current track & \": \" & album of current track\n\
																		end tell"];

		NSAppleEventDescriptor * desc = [script executeAndReturnError:nil];
		
		if (desc != nil && [desc stringValue] != nil)
		{
			NSString * iTunesInfo = [desc stringValue];
				
			NSMutableDictionary * dict = [NSMutableDictionary dictionary];
			[dict setValue:[NSDate date] forKey:@"date"];
			[dict setValue:[NSString stringWithFormat:@"Current iTunes Album: %@", iTunesInfo] forKey:@"name"];
	
			[[NSDistributedNotificationCenter defaultCenter] postNotificationName:DND_UPDATE object:@"iTunesObserver" userInfo:dict];		
		}
	}
}

@end
